package com.yangmf.auto_message_handle.utils;

import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;

import com.yangmf.auto_message_handle.properties.Ali_aiProperties;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;

/**
 * 多模态图像分析工具类
 * 支持本地文件和网络图片路径
 */
@Component
public class ImageAnalysisUtil {
    @Autowired
    private Ali_aiProperties ali_aiProperties;

    
    private final String DEFAULT_MODEL = "qwen3-vl-plus";
    private String DEFAULT_API_KEY ;


    @PostConstruct
    public void init() {
        if (ali_aiProperties != null) {
           this.DEFAULT_API_KEY = ali_aiProperties.getApiKey();
            // 其他初始化逻辑
        }
    }
    /**
     * 分析本地图片文件
     * @param localPath 本地图片路径
     * @param prompt 提示词
     * @return 分析结果
     * @throws ApiException
     * @throws NoApiKeyException
     * @throws UploadFileException
     */
    public  String analyzeLocalImage(String localPath, String prompt)
            throws ApiException, NoApiKeyException, UploadFileException {
        // 处理URL编码字符并转换为标准文件路径
        String decodedPath = localPath.replace("%20", " ");
        File imageFile = new File(decodedPath);

        // 验证文件是否存在
        if (!imageFile.exists()) {
            throw new UploadFileException("文件不存在: " + imageFile.getAbsolutePath());
        }

        String filePath = imageFile.getAbsolutePath();
        return callModel(filePath, prompt);
    }
    
    /**
     * 分析网络图片
     * @param imageUrl 网络图片URL
     * @param prompt 提示词
     * @return 分析结果
     * @throws ApiException
     * @throws NoApiKeyException
     * @throws UploadFileException
     */
    public  String analyzeOnlineImage(String imageUrl, String prompt)
            throws ApiException, NoApiKeyException, UploadFileException {
        // 验证URL有效性
        try {
            new URL(imageUrl);
        } catch (Exception e) {
            throw new UploadFileException("无效的URL地址: " + imageUrl);
        }
        
        return callModel(imageUrl, prompt);
    }
    
    /**
     * 使用默认提示词分析本地图片
     * @param localPath 本地图片路径
     * @return 分析结果
     * @throws ApiException
     * @throws NoApiKeyException
     * @throws UploadFileException
     */
    public  String analyzeLocalImage(String localPath)
            throws ApiException, NoApiKeyException, UploadFileException {
        return analyzeLocalImage(localPath, "请详细描述这张图片的内容");
    }
    
    /**
     * 使用默认提示词分析网络图片
     * @param imageUrl 网络图片URL
     * @return 分析结果
     * @throws ApiException
     * @throws NoApiKeyException
     * @throws UploadFileException
     */
    public String analyzeOnlineImage(String imageUrl)
            throws ApiException, NoApiKeyException, UploadFileException {
        return analyzeOnlineImage(imageUrl, "请详细描述这张图片的内容");
    }
    
    /**
     * 调用多模态模型进行分析
     * @param imagePath 图片路径(本地或网络)
     * @param prompt 提示词
     * @return 分析结果文本
     * @throws ApiException
     * @throws NoApiKeyException
     * @throws UploadFileException
     */
    private  String callModel(String imagePath, String prompt)
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage userMessage = MultiModalMessage.builder()
                .role(Role.USER.getValue())
                .content(Arrays.asList(
                        new HashMap<String, Object>() {{
                            put("image", imagePath);
                        }},
                        new HashMap<String, Object>() {{
                            put("text", prompt);
                        }}))
                .build();

        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(DEFAULT_API_KEY)
                .model(DEFAULT_MODEL)
                .messages(Arrays.asList(userMessage))
                .build();

        MultiModalConversationResult result = conv.call(param);
        return result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text").toString();
    }
}
